import { queryCurrent, query as queryUsers, login, getUserInfo } from '@/services/user';
import { setAuthority } from '@/utils/authority';


const UserModel = {
  namespace: 'user',
  state: {
    currentUser: {},
    streetId: null,
    userInfo: null,
    avatar: "https://gw.alipayobjects.com/zos/antfincdn/XAosXuNZyF/BiazfanxmamNRoxxVxka.png"
  },


  effects: {

    // 登陆
    *login({ payload }, { call, put }) {
      const response = yield call(login, payload);
      // return
      if (response.Status === 1) {
        localStorage.setItem('tk',response.User.Id)
        const userInfo = yield call(getUserInfo, response.User.Id);
        
        const Authority = userInfo[0].IsRoot ? 'admin' : 'guest'
        const streetId = userInfo[0].Streets.length > 0 ? userInfo[0].Streets[0].Id : 'admin'

        const data = {
          Authority,
          streetId,
          userInfo: userInfo[0]
        }
        yield put({
          type: 'saveUserInfo',
          payload: data,
        });
      }
      return response
    },

    *getUser({ payload }, { call, put }) {
        const id = localStorage.getItem('tk')
        const userInfo = yield call(getUserInfo, id);
        const Authority = userInfo[0].IsRoot ? 'admin' : 'guest'
        const streetId = userInfo[0].Streets.length > 0 ? userInfo[0].Streets[0].Id : 'admin'

        const data = {
          Authority,
          streetId,
          userInfo: userInfo[0]
        }
        yield put({
          type: 'saveUserInfo',
          payload: data,
        })

        return {
          status: 200,
          streetId
        }
    },




    *fetch(_, { call, put }) {
      const response = yield call(queryUsers);
      yield put({
        type: 'save',
        payload: response,
      });
    },

    *fetchCurrent(_, { call, put }) {
      const response = yield call(queryCurrent);
      yield put({
        type: 'saveCurrentUser',
        payload: response,
      });
    },
  },


  reducers: {
    saveCurrentUser(state, action) {
      return { ...state, currentUser: action.payload || {} };
    },

    changeNotifyCount(
      state = {
        currentUser: {},
      },
      action,
    ) {
      return {
        ...state,
        currentUser: {
          ...state.currentUser,
          notifyCount: action.payload.totalCount,
          unreadCount: action.payload.unreadCount,
        },
      };
    },

    saveUserInfo(state, { payload }) {
      setAuthority(payload.Authority);
      return { ...state, streetId: payload.streetId, userInfo: payload.userInfo };
    },
  },
};
export default UserModel;
